package org.elasticsearch.plugin.analysis.ik;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.TransportGetAction;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

public class TransportCreateModelFromSetAction extends HandledTransportAction<CreateModelFromSetAction.CreateModelFromSetRequest, CreateModelFromSetAction.CreateModelFromSetResponse> {
    private final static Logger logger = LogManager.getLogger(TransportCreateModelFromSetAction.class);
    private final ClusterService clusterService;
    private final TransportGetAction getAction;

    @Inject
    public TransportCreateModelFromSetAction(Settings settings, ThreadPool threadPool,
                                             TransportService transportService, ActionFilters actionFilters,
                                             IndexNameExpressionResolver indexNameExpressionResolver,
                                             ClusterService clusterService, TransportGetAction getAction) {
        super(settings, CreateModelFromSetAction.NAME, threadPool, transportService,
                actionFilters, indexNameExpressionResolver, CreateModelFromSetAction.CreateModelFromSetRequest::new);
        this.clusterService = clusterService;
        this.getAction = getAction;
    }

    @Override
    protected final void doExecute(CreateModelFromSetAction.CreateModelFromSetRequest request, ActionListener<CreateModelFromSetAction.CreateModelFromSetResponse> listener) {
        throw new UnsupportedOperationException("attempt to execute a TransportCreateModelFromSetAction without a task");
    }

    @Override
    protected void doExecute(Task task, CreateModelFromSetAction.CreateModelFromSetRequest request, ActionListener<CreateModelFromSetAction.CreateModelFromSetResponse> listener) {
        if (!clusterService.state().routingTable().hasIndex(request.getStore())) {
            throw new IllegalArgumentException("Store [" + request.getStore() + "] does not exist, please create it first.");
        }
        GetRequest getRequest = new GetRequest(request.getStore())
                .type(request.getFeatureSetName())
                .id(request.getModelName());
        getRequest.setParentTask(clusterService.localNode().getId(), task.getId());
        getAction.execute(getRequest, ActionListener.wrap((r) -> this.doStore(task, r, request, listener), listener::onFailure));
    }

    private void doStore(Task parentTask, GetResponse response, CreateModelFromSetAction.CreateModelFromSetRequest request,
                         ActionListener<CreateModelFromSetAction.CreateModelFromSetResponse> listener) {
        if (!response.isExists()) {
            throw new IllegalArgumentException("Stored feature set [" + request.getFeatureSetName() + "] does not exist");
        }
        if (request.getExpectedSetVersion() != null && request.getExpectedSetVersion() != response.getVersion()) {
            throw new IllegalArgumentException("Stored feature set [" + request.getFeatureSetName() + "]" +
                    " has version [" + response.getVersion() + "] but [" + request.getExpectedSetVersion() + "] was expected.");
        }
        logger.warn("Plugin response: " + response.getSource());

        listener.onResponse(new CreateModelFromSetAction.CreateModelFromSetResponse("over"));
    }
}
